import { env } from "../../.eslintrc";
import { CanvasButton } from '../component/custombutton'
// chart.js
export class Chart {
  constructor(canvas, width, height, continueCallback) {
    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.width = width;
    this.height = height;
    this.continueCallback = continueCallback;

    this.closeWidth = this.width - 200;
    this.clsoeHeight = 40;
    this.closeX = (this.width - this.closeWidth) / 2;
    this.clsoeY = this.height / 6 * 5;

    this.rankWidth = this.width / 8 * 7;
    this.rankX = (this.width - this.rankWidth) / 2;
    this.rankY = this.height / 3.8; // 排行榜起始Y坐标
    this.rankHeight = this.height - this.rankY - this.height / 8; // 排行榜的高度

    this.records = [];
    this.scrollOffset = 0;
    this.scrollSpeed = 0;
    this.isScrolling = false;
    this.isAnimating = true; // 用于控制动画的运行
    this.button = []; // 用于保存按钮实例

    this.buttonInit();
    this.getRankData(); // province,city,district
    // this.drawPopup();
    setTimeout(() => {
      this.drawPopup();
    }, 30);
  }

  buttonInit() {
    let _this = this;
    this.params = {
      type: "text",
      text: "关闭",
      style: {
        left: this.width / 4,
        top: this.height / 9 * 8,
        width: this.width / 2,
        height: this.height / 20,
        textColor: "black",
        backgroundColor: "lightblue",
        textDecorationLine: "underline"
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          _this.isAnimating = false; // 停止动画
          _this.buttonDestory();
          _this.continueCallback();
        })
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }   
    };
    this.national = {
      type: "text",
      text: "总榜",
      style: {
        backgroundColor: 'white',
        left: this.width / 11,
        top: this.height / 9 * 1.3,
        width: this.width / 5.5,
        height: this.height / 20,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          _this.getRankStronge('');
          _this.buttonDestory();
          _this.national.style.backgroundColor = 'white'
          _this.province.style.backgroundColor = '#CDAF95'
          _this.city.style.backgroundColor = '#CDAF95'
          _this.distr.style.backgroundColor = '#CDAF95'
          _this.drawButton()
        })
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }
    };
    this.province = {
      type: "text",
      text: "省榜",
      style: {
        backgroundColor: '#CDAF95',
        left: this.width / 3.4,
        top: this.height / 9 * 1.3,
        width: this.width / 5.5,
        height: this.height / 20,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          const prov = wx.getStorageSync('province');
          _this.getRankStronge(prov);
          _this.buttonDestory();
          _this.national.style.backgroundColor = '#CDAF95'
          _this.province.style.backgroundColor = 'white'
          _this.city.style.backgroundColor = '#CDAF95'
          _this.distr.style.backgroundColor = '#CDAF95'
          _this.drawButton()
        })
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }
    };
    this.city = {
      type: "text",
      text: "市榜",
      style: {
        backgroundColor: '#CDAF95',
        left: this.width / 1.95,
        top: this.height / 9 * 1.3,
        width: this.width / 5.5,
        height: this.height / 20,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          const ct = wx.getStorageSync('city');
          _this.getRankStronge(ct);
          _this.buttonDestory();
          _this.national.style.backgroundColor = '#CDAF95'
          _this.province.style.backgroundColor = '#CDAF95'
          _this.city.style.backgroundColor = 'white'
          _this.distr.style.backgroundColor = '#CDAF95'
          _this.drawButton()
        })
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }
    };
    this.distr = {
      type: "text",
      text: "区榜",
      style: {
        backgroundColor: '#CDAF95',
        left: this.width / 1.39,
        top: this.height / 9 * 1.3,
        width: this.width / 5.5,
        height: this.height / 20,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10,
      },
      success(button) {
        _this.button.push(button);
        button.drawButton(_this.context); // 绘制按钮
        button.onTap((res) => {
          const dis = wx.getStorageSync('district');
          _this.getRankStronge(dis);
          _this.buttonDestory();
          _this.national.style.backgroundColor = '#CDAF95'
          _this.province.style.backgroundColor = '#CDAF95'
          _this.city.style.backgroundColor = '#CDAF95'
          _this.distr.style.backgroundColor = 'white'
          _this.drawButton();
        })
      },
      fail(res) {
        console.log("创建失败", res.errMsg);
      }
    };

  }

  getRankData(path) {
    const getString = path || '';
    wx.cloud.init({
      env: 'prod-8gf88ck5bb3ddd38'
    })
    wx.cloud.callContainer({
      "config": {
        "env": "prod-8gf88ck5bb3ddd38"
      },
      "path": `/apis/ranks/selectRankInfo${getString}`,
      "header": {
        'content-type': 'application/json',
        'AuthToken': wx.getStorageSync("AuthToken"),
        "X-WX-SERVICE": env.service
      },
      "method": "GET",
      success: (res) => {
        this.records = res.data.result.map(item => {
          let nickName = item.nickName;
          if (nickName.length > 5) {
            nickName = nickName.substring(0, 5) + '...';
          }
          return {
            nickName: nickName,
            completeTime: item.completeTime
          };
        });
        wx.setStorage({
          key: 'rankData',
          data: res.data.result,
          success: function (res) {
            console.log('rankdata存储成功', res);
          },
          fail: function (err) {
            console.error('rankdata存储失败', err);
          }
        })
      },
      fail: console.warn,
    })
  }

  getRankStronge(area) {
    const result = wx.getStorageSync('rankData');
    let foundItems = [];
    if(area === '') {
      foundItems = result;
    } else {
      result.forEach(item => {
        if (item.city === area || item.province === area || item.district === area) {
          foundItems.push({
            nickName: item.nickName,
            completeTime: item.completeTime
          });
        }
      });
    }
    this.records = foundItems.map(item => {
      let nickName = item.nickName;
      if (nickName.length > 5) {
        nickName = nickName.substring(0, 5) + '...';
      }
      return {
        nickName: nickName,
        completeTime: item.completeTime
      };
    });
  }

  drawPopup() {
    this.drawModal();
    wx.onTouchStart((event) => this.onTouchStart(event));
    wx.onTouchMove((event) => this.onTouchMove(event));
    wx.onTouchEnd(() => this.onTouchEnd());
  }

  onTouchStart(event) {
    if (event.touches && event.touches[0]) {
      this.touchStartY = event.touches[0].clientY;
      this.isScrolling = true;
      this.scrollSpeed = 0; // Reset the scroll speed when a new touch starts
    } else {
      console.warn("TouchStart event does not have touches[0]");
    }
  }

  onTouchMove(event) {
    if (event.touches && event.touches[0]) {
      const touchY = event.touches[0].clientY;
      const deltaY = touchY - this.touchStartY;
      this.touchStartY = touchY;
      this.scrollOffset += deltaY;

      // 限制滚动范围
      this.scrollOffset = Math.min(0, this.scrollOffset); // 不允许向下超出顶部
      const maxOffset = -((this.records.length * 35) - (this.height - this.clsoeY));
      this.scrollOffset = Math.max(maxOffset, this.scrollOffset); // 不允许向上超出底部
      this.scrollSpeed = deltaY;
    } else {
      console.warn("TouchMove event does not have touches[0]");
    }
  }

  onTouchEnd() {
    this.isScrolling = false;
  }

  animate() {
    if (this.isAnimating) {
      if (!this.isScrolling) {
        // Apply friction to the scroll speed for smooth scrolling
        this.scrollSpeed *= 0.95;
        this.scrollOffset += this.scrollSpeed;
        this.scrollOffset = Math.min(0, this.scrollOffset);
        const maxOffset = -((this.records.length * 35) - this.rankHeight);
        this.scrollOffset = Math.max(maxOffset, this.scrollOffset);

        // 确保 scrollSpeed 和 scrollOffset 是数值
        if (isNaN(this.scrollSpeed)) {
          this.scrollSpeed = 0;
          console.error("scrollSpeed is NaN, resetting to 0");
        }
        if (isNaN(this.scrollOffset)) {
          this.scrollOffset = 0;
          console.error("scrollOffset is NaN, resetting to 0");
        }
      }
      this.drawRankList();
      requestAnimationFrame(() => this.animate());
    }
  }

  drawRankList() {
    const modalX = this.rankX;
    const modalY = this.rankY;
    const modalWidth = this.rankWidth;
    const modalHeight = this.rankHeight;
    this.context.clearRect(this.rankX, this.rankY, this.rankWidth, this.rankHeight);
    // 绘制排行榜区域背景
    this.context.fillStyle = '#edd1d8'; // 设置你想要的背景颜色
    this.context.fillRect(modalX, modalY, modalWidth, modalHeight);

    let totalRecordsHeight = this.records.length * 35;
    let startY = null;

    if (totalRecordsHeight < modalHeight) {
      // 如果记录总高度小于可用高度，居中显示
      startY = modalY + (modalHeight - totalRecordsHeight) / 2;
    } else {
      startY = modalY + this.scrollOffset;
    }

    if (this.records === '') {
      this.context.fillStyle = 'black';
      this.context.fillText("还没通关呢！！！你们也不行吖！！！", this.width / 2, this.height / 2);
    } else {
      this.records.forEach((record, index) => {
        if (startY >= modalY && startY <= modalY + modalHeight - 35) { // 只绘制在可见区域内的记录
          this.context.fillStyle = '#e4c6d0';
          this.context.fillRect(modalX, startY, modalWidth, 30);
          this.context.fillStyle = 'black';
          // 绘制排名
          this.context.fillText(`${index + 1}`, this.width / 6, startY + 20);
          // 绘制昵称
          this.context.fillText(record.nickName, this.width / 5 * 2, startY + 20);
          // 绘制通关时间
          this.context.fillText(record.completeTime, this.width / 4 * 3, startY + 20);
        }
        startY += 35;
      });
    }

  }

  drawModal() {
    let _this = this;
    const modalWidth = this.width / 8 * 7;
    const modalHeight = this.height / 5 * 4.5;
    const modalX = (this.width - modalWidth) / 2;
    const modalY = (this.height - modalHeight) / 2;

    this.context.fillStyle = '#edd1d8'; // 设置你想要的背景颜色
    this.context.fillRect(modalX, modalY, modalWidth, modalHeight);

    this.context.font = '24px Arial';
    this.context.fillStyle = 'black';
    this.context.textAlign = 'center';
    this.context.fillText('排行榜', this.width / 2, this.height / 9);
    this.context.font = '16px Arial';
    this.context.fillStyle = 'black';
    this.context.textAlign = 'center';
    this.context.fillText('排名', this.width / 6, this.height / 4);
    this.context.font = '16px Arial';
    this.context.fillStyle = 'black';
    this.context.textAlign = 'center';
    this.context.fillText('昵称', this.width / 5 * 2, this.height / 4);
    this.context.font = '16px Arial';
    this.context.fillStyle = 'black';
    this.context.textAlign = 'center';
    this.context.fillText('通关时间', this.width / 4 * 3, this.height / 4);
    this.drawButton();
    this.drawRankList();
    this.animate(); // 动画开始
  }

  drawButton() {
    new CanvasButton(this.params);
    new CanvasButton(this.national);
    new CanvasButton(this.province);
    new CanvasButton(this.city);
    new CanvasButton(this.distr);
  }

  buttonDestory() {
    if (this.button) {
      this.button.forEach(element => {
        element.destroy();
      })
      // this.button = null;
    }
  }

  closeButtonClick() {
    this.isAnimating = false; // 停止动画
    this.context.clearRect(0, 0, this.width, this.height); // 清除画布
    this.continueCallback();
    this.buttonDestory();
  }


}
